<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="${ctx}/static/js/aws/aws-sdk-2.428.0.min.js"></script>
<script src="${ctx}/static/js/jquery/jquery-1.8.3.min.js"></script>
<script src="${ctx}/static/js/im.js"></script>
  <style type="text/css">
       html, body {
           margin: 0px;
           padding: 0px;
           width: 100%;
           height: 100%;
           background-color: #f8f7f7;
           font-family: arial,sans-serif;
       }

       #layouttable {
           margin:0px;
           padding:0px;
           width:100%;
           height:100%;
           border:2px solid green;
           border-collapse:collapse;
           min-width:800px;
       }

           #layouttable td {
               border: 1px solid green;
           }

       .h100p {
           height:100%;
       }

       .midtr{height:auto;}
           .midtr tr td {
               height: 100%;
           }

       #chatmsgbox, #chatonlinebox ,#chatonlinebox2{
           background-color:white;
           overflow-x: hidden;
           overflow-y: auto;
           overflow-wrap: break-word;
           height: 100%;
       }

       #chatonlinebox,#chatonlinebox2 {
           background-color:#f5d0a8;
       }

       .rc, .sd {
           overflow:hidden;
       }

        .rc p {
           float: left;
           color: green;
       }
           .sd p {
               float: right;
               color: orange;
           }
   </style>
<script>
//对Date的扩展，将 Date 转化为指定格式的String   
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
//例子：   
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.Format = function(fmt)   
{ //author: meizz   
var o = {   
 "M+" : this.getMonth()+1,                 //月份   
 "d+" : this.getDate(),                    //日   
 "h+" : this.getHours(),                   //小时   
 "m+" : this.getMinutes(),                 //分   
 "s+" : this.getSeconds(),                 //秒   
 "q+" : Math.floor((this.getMonth()+3)/3), //季度   
 "S"  : this.getMilliseconds()             //毫秒   
};   
if(/(y+)/.test(fmt))   
 fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
for(var k in o)   
 if(new RegExp("("+ k +")").test(fmt))   
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
return fmt;   
}

var contactsMap=new Map();
var baseUrl='${ctx}';
IM.baseUrl = baseUrl;
IM.onerror=function(data){
	alert("im 处理失败");
}
IM.chatMessageHandler = function(message){
	console.log("chatMessageHandler:"+JSON.stringify(message));
	var content = message.content;
	var type = message.type;
	
	var obj = contactsMap.get(message.fromId);
	var name = obj.name;
	
	if(type == 2){//图片
		var img ='<img height="20" width="20" src="'+content+'"></img>';
		content = img;
	}
	var html = "<div id="+message.id+">";
	html+=name+"说:"+content;
		html+="</div>";
	$("#chatmsgbox").append(html);
};
IM.sysMessageHandler = function(message){
	console.log("sysMessageHandler:"+JSON.stringify(message));
	if(message.type == 1){//消息撤回
		var obj = message.content;
		$("#"+obj.msgid).text("对方撤回了消息");
	}
};
function login(){
	var phone = $("#login_username").val();
	var password = $("#login_pwd").val();
	IM.login({
		password:password,
		phone:phone
	}).then(function(data){
		if(data.code == 1){
			alert("登录成功");
		}else{
			alert("失败 code:"+data.code);
		}
	}).catch(function(data){
		alert("登录失败");
	});
}

function getContacts(){
	IM.getContacts().then(function(data){
		if(data.code == 1){
			var obj = data.obj;
			var chatnames = $("#chatnames");
			for ( var i = 0; i <obj.length; i++){
				var image = obj[i].image;
				var name = obj[i].name;
				var rid = obj[i].rid;
				contactsMap.set(rid,obj[i]);
				var html='<li style="cursor:pointer" onclick="setMsgLable('+rid+')">';
				html+='<img height="20" width="20" src="'+image+'"/>';
				html+='<span>'+name+'</span>';
				html+='</li>';
				
				chatnames.append(html);
			}
			IM.wsConnect();//好友获取完成之后,连接socket
		}else{
			alert("失败 code:"+data.code);
		}
	}).catch(function(data){
		alert("获取失败");
		console.log(data);
	});
}
function setMsgLable(rid){
	var obj = contactsMap.get(rid);
	var name = obj.name;
	var rid = obj.rid;
	$("#msgLabel").text("正在发送给:"+name);
	$("#msgLabel").attr("rid",rid);
	
}
function getClientid() {
     return (Math.random()*10000000).toString(16).substr(0,4)+'-'+(new Date()).getTime()+'-'+Math.random().toString().substr(2,5);
}
function revokeMessage(msgdiv){
	var msgid = $(msgdiv).attr("id");
	alert(msgid);
	IM.revokeMessage({
		msgid:msgid
	}).then(function(data){
		if(data.code == 1){
			$(msgdiv).text("你撤回了一条消息");
		}else{
			alert("失败 code:"+data.code);
		}
	}).catch(function(data){
		alert("发送失败");
	});
}
function sendMsg(location){
	var rid = $("#msgLabel").attr("rid");
	if(!rid){
		alert("请选择需要发送的人");
		return;
	}
	if(location){
		var img ='<img height="20" width="20" src="'+location+'"></img>';
		IM.sendMsg({
			to:rid,
	    	content:location,
	    	clientid:getClientid(),
	    	type:2,
	    	chatType:1
		}).then(function(data){
			if(data.code == 1){
				var html = '<div id='+data.obj.id+' style="cursor:pointer" onclick="revokeMessage(this)">';
				html+='我说:'+img;
					html+='</div>';
				$("#chatmsgbox").append(html);
			}else{
				alert("失败 code:"+data.code);
			}
		}).catch(function(data){
			alert("发送失败");
		});
	}else{
		var msg = $("#msg").val();
		IM.sendMsg({
			to:rid,
	    	content:msg,
	    	clientid:getClientid(),
	    	type:1,
	    	chatType:1
		}).then(function(data){
			if(data.code == 1){
				var html = '<div id='+data.obj.id+' style="cursor:pointer" onclick="revokeMessage(this)">';
				html+='我说:'+msg;
					html+='</div>';
				$("#chatmsgbox").append(html);
			}else{
				alert("失败 code:"+data.code);
			}
		}).catch(function(data){
			alert("发送失败");
		});
	}
}
function getSession(){
	IM.getSession().then(function(data){
		if(data.code == 1){
			console.log(data.obj);
			var obj = data.obj;
			var chatnames = $("#chatnames2");
			for ( var i = 0; i <obj.length; i++){
				var uptime = obj[i].uptime;
				var rid = obj[i].rid;
				var content = obj[i].content;
				var noreadnum = obj[i].noreadnum;
				var contentObj = JSON.parse(content);
				var contentStr ="";
				if(contentObj.rev == 1){//撤回消息
					if(contentObj.f == IM.userid){//如果是自己
						contentStr = "你撤回了一条消息";
					}else{
						contentStr = "对方撤回了一条消息";
					}
				}else{
					contentStr = contentObj.content;
				}
				var contacts = contactsMap.get(rid);
				var image = contacts.image;
				var name = contacts.name;
				var html='<li style="cursor:pointer" onclick="setMsgLable('+rid+')">';
				html+='<img height="20" width="20" src="'+image+'"/>';
				html+='<span>'+name+'</span>';
				html+='<span>未读:'+noreadnum+'</span>';
				html+='<span>内容:'+contentStr+'</span>';
				html+='<span>时间:'+new Date(uptime).Format("yyyy-MM-dd hh:mm:ss")+'</span>';
				html+='</li>';
				
				chatnames.append(html);
			}
		}else{
			alert("失败 code:"+data.code);
		}
	}).catch(function(data){
		alert("获取失败");
		console.log(data);
	});
}
/*
IM.sendMsg({
	to:"4",
	content:"111",
	clientid:"cli1",
	type:1
}).then(function(data){
	console.log("send msng succ"+data);
	alert("发送成功");
}).catch(function(data){
	console.log("send msng err"+data);
	alert("发送失败");
});
*/

function uploadFile(){
	var f = document.getElementById("file").files[0];
	var p = "userinfo/"+IM.userid+"/";
	var params = {
		file:f,
		path:p
	}
	IM.upload(params).then(function(data){
		 console.log("Upload Success", data);
		//var img ="<img src='"+data.Location+"'></img>";
		sendMsg(data.Location);
	}).catch(function(data){
		 console.log("Error", data);
		 alert('上传失败');
	});
}
</script>
<title>s3测试</title>

</head>

<body>
<div id="login">
	<label>用户名</label><input id="login_username" type="text" />
	<label>密码</label><input id="login_pwd" type="text" /><br />
	<button id="login_bt"  onclick="login()">登录</button><br />
	<button onclick="getContacts()">点击获取联系人列表</button><br />
	<button onclick="getSession()">点击获取最近会话列表</button><br />
</div>
<div id="contacts"></div>

<div id="rigth" style="float:left;width: 1000;height: 500px; ">
    <table id="layouttable">
        <colgroup>
            <col style="width:auto" />
            <col style="width: 200px;" />
            <col style="width: 400px;" />
        </colgroup>
        <tr style="height:auto;" id="midtr">
            <td>
                <div id="chatmsgbox">
                </div>
            </td>
            <td>
                <div id="chatonlinebox">
                    <ul id="chatnames">
                    </ul>
                </div>
            </td>
            <td>
                <div id="chatonlinebox2">
                    <ul id="chatnames2">
                    </ul>
                </div>
            </td>
        </tr>
        <tr style="height:50px;">
            <td colspan="3">
                <label id="msgLabel" for="msg">输入内容：</label>
                <input type="text" id="msg" style="width:400px;" />
                <input type="button" onclick="sendMsg()" value="发送消息" />
                <input id="file" type="file" /><br />
				<input type="button" onclick="uploadFile()" value="上传到S3" />
            </td>
        </tr>
    </table>
</div>

</body>
</html>